package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"niu-video/config"
	"sync"
)

var DB *gorm.DB

// once 确保全局的 db 对象只实例一次
var once sync.Once

func InitDb() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&collation=%s&%s",
		config.Conf.Mysql.Username,
		config.Conf.Mysql.Password,
		config.Conf.Mysql.Host,
		config.Conf.Mysql.Port,
		config.Conf.Mysql.Database,
		config.Conf.Mysql.Charset,
		config.Conf.Mysql.Collation,
		config.Conf.Mysql.Query,
	)
	once.Do(func() {
		db, err := gorm.Open(mysql.Open(dsn))
		if err != nil {
			panic(fmt.Errorf("初始化mysql数据库异常: %v", err))
		}
		// 开启mysql日志
		if config.Conf.Mysql.LogMode {
			db.Debug()
		}
		// 全局DB赋值
		DB = db
	})

}
